import React, { useContext, useEffect, useMemo, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { UserContext } from '../context/User';
import { StatusContext } from '../context/Status';
import {
  API,
  getLogo,
  getSystemName,
  isAdmin,
  isMobile,
  showError
} from '../helpers';
import '../index.css';
import {
  IconCalendarClock,
  IconChecklistStroked,
  IconComment,
  IconCreditCard,
  IconGift,
  IconHistogram,
  IconHome,
  IconImage,
  IconKey,
  IconLayers,
  IconPriceTag,
  IconSetting,
  IconUser
} from '@douyinfe/semi-icons';
import { Layout, Nav } from '@douyinfe/semi-ui';
import { setStatusData } from '../helpers/data.js';

const SiderBar = () => {
  const isMobileDevice = isMobile();

  if (!isMobileDevice) {
    return null;
  }

  const [userState, userDispatch] = useContext(UserContext);
  const [statusState, statusDispatch] = useContext(StatusContext);
  const defaultIsCollapsed = localStorage.getItem('default_collapse_sidebar') === 'true';

  let navigate = useNavigate();
  const [selectedKeys, setSelectedKeys] = useState(['home']);
  const systemName = getSystemName();
  const logo = getLogo();
  const [isCollapsed, setIsCollapsed] = useState(defaultIsCollapsed);

  const routerMap = {
    home: '/',
    channel: '/channel',
    token: '/token',
    redemption: '/redemption',
    topup: '/topup',
    user: '/user',
    log: '/log',
    midjourney: '/midjourney',
    setting: '/setting',
    about: '/about',
    chat: '/chat',
    detail: '/detail',
    pricing: '/pricing',
    task: '/task'
  };

  // 预定义所有可能的按钮
  const allButtons = [
    { text: '首页', itemKey: 'home', to: '/', icon: <IconHome /> },
    { text: '聊天', itemKey: 'chat', to: '/chat', icon: <IconComment /> },
    { text: '模型价格', itemKey: 'pricing', to: '/pricing', icon: <IconPriceTag /> },
    { text: '令牌', itemKey: 'token', to: '/token', icon: <IconKey /> },
    { text: '钱包', itemKey: 'topup', to: '/topup', icon: <IconCreditCard /> },
    { text: '日志', itemKey: 'log', to: '/log', icon: <IconHistogram /> },
    { text: '设置', itemKey: 'setting', to: '/setting', icon: <IconSetting /> },
    { text: '渠道', itemKey: 'channel', to: '/channel', icon: <IconLayers /> },
    { text: '兑换码', itemKey: 'redemption', to: '/redemption', icon: <IconGift /> },
    { text: '用户管理', itemKey: 'user', to: '/user', icon: <IconUser /> },
    { text: '数据看板', itemKey: 'detail', to: '/detail', icon: <IconCalendarClock /> },
    { text: '绘图', itemKey: 'midjourney', to: '/midjourney', icon: <IconImage /> },
    { text: '异步任务', itemKey: 'task', to: '/task', icon: <IconChecklistStroked /> }
  ];

  // 判断用户是否为管理员
  const isUserAdmin = isAdmin();
  const isLoggedIn = !!userState.user;
  console.log('isUserAdmin:', isUserAdmin); // 调试输出

  // 根据用户状态动态设置导航按钮
  const headerButtons = useMemo(() => {
    console.log('userState.isLoggedIn:', isLoggedIn); // 调试输出

    if (!isLoggedIn) {
      // 未登录用户
      return allButtons.filter((btn) =>
        ['home', 'pricing', 'chat'].includes(btn.itemKey)
      );
    } else if (isUserAdmin) {
      // 超级管理员
      console.log('超级管理员按钮被加载'); // 调试输出
      return allButtons.filter((btn) =>
        [
          'home',
          'token',
          'topup',
          'channel',
          'redemption',
          'user',
          'detail',
          'midjourney',
          'task',
          'pricing',
          'log',
          'chat',
          'setting'
        ].includes(btn.itemKey)
      );
    } else {
      // 普通用户
      return allButtons.filter((btn) =>
        ['home', 'chat', 'token', 'topup', 'log', 'setting', 'pricing'].includes(
          btn.itemKey
        )
      );
    }
  }, [isLoggedIn, isUserAdmin]);

  const loadStatus = async () => {
    const res = await API.get('/api/status');
    if (res === undefined) {
      return;
    }
    const { success, data } = res.data;
    if (success) {
      statusDispatch({ type: 'set', payload: data });
      setStatusData(data);
    } else {
      showError('无法正常连接至服务器！');
    }
  };

  useEffect(() => {
    loadStatus().then(() => {
      setIsCollapsed(
        isMobileDevice ||
        localStorage.getItem('default_collapse_sidebar') === 'true'
      );
    });
    let localKey = window.location.pathname.split('/')[1];
    if (localKey === '') {
      localKey = 'home';
    }
    setSelectedKeys([localKey]);
  }, [isMobileDevice, userState.isLoggedIn]);

  return (
    <Layout>
      <div style={{ height: '100%' }}>
        <Nav
          style={{ maxWidth: 200 }}
          defaultIsCollapsed={defaultIsCollapsed}
          isCollapsed={isCollapsed}
          onCollapseChange={(collapsed) => {
            setIsCollapsed(collapsed);
          }}
          selectedKeys={selectedKeys}
          renderWrapper={({ itemElement, isSubNav, isInSubNav, props }) => {
            return (
              <Link
                style={{ textDecoration: 'none' }}
                to={routerMap[props.itemKey]}
              >
                {itemElement}
              </Link>
            );
          }}
          items={headerButtons.map(button => ({
            itemKey: button.itemKey,
            text: button.text,
            icon: button.icon
          }))}
          onSelect={(key) => {
            setSelectedKeys([key.itemKey]);
          }}
          header={{
            logo: (
              <img src={logo} alt='logo' style={{ marginRight: '0.75em' }} />
            ),
            text: systemName
          }}
        >
          <Nav.Footer collapseButton={true}></Nav.Footer>
        </Nav>
      </div>
    </Layout>
  );
};

export default SiderBar;
